/*================================================================
*   Copyright (C) 2021 Sangfor Ltd. All rights reserved.
*   
*   文件名称：music_player.hpp
*   创 建 者：wudu
*   创建日期：2021年08月26日
*   描    述：
*
================================================================*/
#pragma once

#include <stdio.h>
#include <iostream>
#include <string>

#include <jsoncpp/json/json.h>
#include "httplib.h"
#include "database.hpp"
#include "session.hpp"

using namespace std;
using namespace httplib;

#define MUSIC_SVR_IP "0.0.0.0"
#define MUSIC_SVR_PORT 18989

class MusicServer
{
    public:
        MusicServer()
        {
            svr_ip_ = MUSIC_SVR_IP;
            svr_port_ = MUSIC_SVR_PORT;

            db_svr_ = NULL;
            all_sess_ = NULL;
        }

        ~MusicServer()
        {}

        //1.初始化类接口
        int InitMusicServer(string db_ip, uint16_t db_port, string db_user, string db_passwd, string db_db, string ip = MUSIC_SVR_IP, uint16_t port = MUSIC_SVR_PORT)
        {
            svr_ip_ = ip;
            svr_port_ = port;

            //DataBaseSvr(const string& db_host, const string& db_user, const string& db_password, const string& db_name    , unsigned int db_port = 3306)
            db_svr_ = new DataBaseSvr(db_ip, db_user, db_passwd, db_db, db_port);
            if(db_svr_ == NULL)
            {
                return -1;
            }

            if(db_svr_->ConnectToMysql() < 0)
            {
                return -2;
            }


            all_sess_ = new AllSessionInfo();
            if(all_sess_ == NULL)
            {
                return -3;
            }
            return 0;
        }
        //2.启动服务的接口
        void StartMusicServer()
        {
            //1.注册若干个http请求对应的 回调函数
            /*
             * 请求：{"name":"xxx","passwd":"xxx","email":"xxxxx","phonenum":"xxxxxxx"}
             * 响应：{"register_status":"xxxx"}
             * */
            http_svr_.Post("/register", [this](const Request& req, Response& resp){
                    //1.将用户提交的数据， 继续反序列化， 拿到一个json对象
                    Json::Reader r;
                    Json::Value v;
                    r.parse(req.body, v);

                    Json::Value resp_json;
                    //2.需要将浏览器提交的数据继续持久化（保存在数据库当中）
                    resp_json["status"] = db_svr_->InsertUserInfo(v);

                    Json::FastWriter w;
                    resp.body = w.write(resp_json);
                    resp.set_header("Content-Type", "application/json");
                    });

            http_svr_.Post("/login", [this](const Request& req, Response& resp){
                   cout << req.body << endl;  
                   /*
                    * 1.将浏览器提交的json串，反序列化成为json对象
                    * 2.调用数据库模块的函数， 进行查找和比对
                    *    有邮箱继续查找， 用密码进行比对
                    * 3.根据登录状态， 判断是否生成会话信息
                    * 4.返回给浏览器一个结果
                    *     4.1 登录失败
                    *     4.2 登录成功
                    *         需要返回会话ID
                    * */
                    Json::Reader r;
                    Json::Value v;
                    r.parse(req.body, v);

                    Json::Value resp_json;
                    int user_id = db_svr_->QueryUserExist(v);
                    string session_id = "";
                    if(user_id > 0)
                    {
                        Session sess(v, user_id);
                        //保存该会话信息
                        session_id = sess.GetSessionID();
                        all_sess_->InsertSessionInfo(session_id, sess);
                    }

                    resp_json["login_status"] = user_id > 0 ? true : false;
                    Json::FastWriter w;
                    resp.body = w.write(resp_json);
                    resp.set_header("Set-Cookie", session_id.c_str());
                    resp.set_header("Content-Type", "application/json");
                    });

            
            http_svr_.Get("/findMusic", [this](const Request& req, Response& resp){
                    //1.会话校验
                    Json::Value resp_json;
                    int user_id = all_sess_->CheckSession(req);
                    if(user_id <= 0)
                    {
                        resp_json["status"] = -1;
                    }
                    else
                    {
                        resp_json["status"] = user_id;
                    }
                    //2.查询音乐
                    db_svr_->GetMusic(resp_json);

                    cout << resp_json << endl;
                    //3.组织响应
                    Json::FastWriter w;
                    resp.body = w.write(resp_json);
                    resp.set_header("Content-Type", "application/json");
                    });
            http_svr_.Post("/loveMusic", [this](const Request& req, Response& resp){
                    Json::Value resp_json;
                    int user_id = all_sess_->CheckSession(req);
                    if(user_id <= 0)
                    {
                        resp_json["status"] = -1;
                    }
                    else
                    {
                        resp_json["status"] = 0;
                        
                    }

                    });

            //2.设置http服务器的静态路径（逻辑的根目录）
            http_svr_.set_mount_point("/", "./web");
            //3.监听起来
            http_svr_.listen(svr_ip_.c_str(), svr_port_);
        }
    private:
        // httplib 当中的server 
        Server http_svr_;

        string svr_ip_;
        uint16_t svr_port_;

        //数据库操作模块
        DataBaseSvr* db_svr_;

        AllSessionInfo* all_sess_;
};

